package com.qf.push.controller;

import com.qf.base.push.MessageDTO;
import com.qf.base.result.R;
import com.qf.push.model.Message;
import com.qf.push.service.PushService;
import com.qf.push.web.server.WebSocketServer;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;

@RestController
@RequestMapping("/push")
public class PushController {
    @Resource
    private WebSocketServer socketServer;
    @Resource
    private PushService pushService;


    @PostMapping("/send")
    public R send(@RequestBody MessageDTO messageDTO){
        String uid=messageDTO.getUid()+"";
        String message=messageDTO.getMessage();
        int type=messageDTO.getType();//类型
        Long requestId = messageDTO.getRequestId();
        //判断请求id是否再数据库中存在，如果存在就不可用，如果不存在就可用，
        if (pushService.isIdem(requestId)){
            //判定用户是否在线，在线发送，不在线不发送
            boolean result = socketServer.sendInfo(uid, message);
            Message msg=new Message();
            msg.setContent(message);
            msg.setUid(Long.parseLong(uid));
            msg.setType(type);
            if (result){
                //发送成功的消息设置 seate为1
                msg.setState(1);
                pushService.saveMessage(msg,requestId);
                return  R.ok(200,"用户在线，推送成功");
            }else {
                msg.setState(0);
                pushService.saveMessage(msg,requestId);
                return R.ok(201,"用户离线，推送任务已经设置");
            }
        }else {
            return R.ok(200,"已经推送成功");
        }

    }

}
